<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style ref="stylesheet" type="text/css">
  .main{
    background: powderblue;
    /* height: 500px; */
    width: 500px;
    margin: 40px;
    text-align: center;
  }
  </style>
</head>
<body>
  <div class="main">
    <p id="inText"></p>
    <img src="img/1.jpg">
    <button id="button1">上一张</button>
    <button id="button2">下一张</button>
  </div>
  <script type="text/javascript">
  var button1 = document.getElementById('button1')
  var button2 = document.getElementById('button2')

  /*
  * 要切换图片就是要修改img标签的src属性
  */
//  这里通过tag获得的一定是个数组，所以要想获取图片，必须是数组的第一个元素
 var img = document.getElementsByTagName('img')[0]
 //创建一个数组，用来保存图片的路径
 var imgArr = ["img/1.jpg" , "img/2.jpg" , "img/3.jpg" , "img/4.jpg" ,"img/5.jpg"];
//创建一个变量，来保存当前正在显示的图片的索引
  var imgIndex = 0;  
 var inText = document.getElementById('inText')
  inText.innerHTML = "一共有"+imgArr.length+"张图片，当前为第"+(imgIndex+1)+"张图片"

  window.onload = function () {
      button1.onclick = function () {

      /*
        * 切换到上一张，索引自减
        */
        imgIndex--;

      //判断index是否小于0
      if(imgIndex < 0){
        imgIndex = imgArr.length - 1;
      }

      img.src = imgArr[imgIndex];
      console.log(img.src)
      inText.innerHTML = "一共"+imgArr.length+"张图片，当前为第"+(imgIndex+1)+"张图片"

      };
      button2.onclick = function () {
      if (imgIndex==4) {
        imgIndex = 0
      } else {
        imgIndex++
      }
      img.src = imgArr[imgIndex]
      inText.innerHTML = "一共"+imgArr.length+"张图片，当前为第"+(imgIndex+1)+"张图片"

      };
  };

  </script>
  
</body>
</html>